﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataSync.Entity;
using System.Data;
using System.Data.SqlClient;
using DataSync.Common;

namespace DataSync.Proc.Writer
{
    class SqlServerDBWriter : DBWriter
    {
        private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        protected override void DBInsert(IList<Dictionary<string, ColData>> data, IDbConnection conn)
        {
            var myconn = conn as SqlConnection;
            if (string.IsNullOrEmpty(base.CurOutputDbConf.TableName))
            {
                throw new ApplicationException("OutputDBSqlServer 配置错误：TableName不能为空");
            }

            var dt = ConvertToDT(data);
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(myconn))
            {
                bulkCopy.BatchSize = dt.Rows.Count;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    bulkCopy.ColumnMappings.Add(j, dt.Columns[j].ColumnName);
                }
                bulkCopy.DestinationTableName = base.CurOutputDbConf.TableName;
                bulkCopy.WriteToServer(dt);
            }
        }

        private DataTable ConvertToDT(IList<Dictionary<string, ColData>> data)
        {
            var dt = new DataTable();
            foreach (var col in data[0])
            {
                dt.Columns.Add(new DataColumn(col.Key, DBFactory.GetSysType(col.Value.FieldType)));
            }
            foreach (var row in data)
            {
                var dr = dt.NewRow();
                foreach (var col in row)
                {
                    dr[col.Key] = DataTypeHelper.ConvertToType(col.Value.FieldType, col.Value.Value);
                }

                dt.Rows.Add(dr);
            }
            return new DataTable();
        }
    }
}
